package com.catmiw.stock2013.util;

import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.catmiw.stock2013.domain.CapitalChange;
import com.catmiw.stock2013.domain.Earnings;
import com.catmiw.stock2013.domain.Stock;
import com.catmiw.stock2013.domain.StockInfo;
import com.catmiw.stock2013.util.dbf.DBFException;
import com.catmiw.stock2013.util.dbf.DBFReader;

public class StockFileUtils {
	private static String[] VALIDHEAD={"SZ0","SZ30","SH6","SH999999","SZ399001"};
	
	/**
	 * 从证券文件中取证券代码和名称
	 * @return
	 */
	public static List<Stock> stockListFromFile(){
		List<Stock> stocklist=new ArrayList<Stock>();
		String filename=PropertyManager.getProperty("SZStockNameFile");
		stockListFromFile(stocklist,"SZ",filename);
		
		filename=PropertyManager.getProperty("SHStockNameFile");
		stockListFromFile(stocklist,"SH",filename);
		
		Collections.sort(stocklist);
		
		return stocklist;
	}
	
	/**
	 * 从证券文件中取证券代码和名称
	 * @return
	 */
	private static void stockListFromFile(List<Stock> stocklist,String market, String fn) {
		if (fn == null)
			return;

		java.io.RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(fn, "r");
			raf.seek(50); // 文件头
			byte[] b = new byte[250];
			String sname = null;
			while (raf.read(b) != -1) {
				byte[] rid = new byte[6];
				for (int i = 0; i < 6; i++) {
					rid[i] = b[i];
				}
				int end = 0;
				for (int i = 24; i < 250; i++) {
					if (b[i] == 0) {
						end = i;
						break;
					}
				}
				if (end <= 24) {
					sname = null;
				} else {
					sname = new String(b, 24, end - 24,"GBK");
				}
				String code=new String(rid);
				String id=market+code;
				for (String s:VALIDHEAD){
					if (id.startsWith(s)){
						Stock stock=new Stock();
						stock.setCode(code);
						stock.setId(id);
						stock.setName(sname);
						stock.setStockinfo(new StockInfo());
						stocklist.add(stock);
						break;
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				raf.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private static List<Map<String,String>> dbfToMapList(String dbfFile){
		List<Map<String,String>> lm=new ArrayList<Map<String,String>>();
		
		try {
			DBFReader dbfreader = new DBFReader(dbfFile);
			String field[]=new String[dbfreader.getFieldCount()];
			for (int b = 0; b < dbfreader.getFieldCount(); b++) {
				field[b]=dbfreader.getField(b).getName().trim().toUpperCase();
			}

			while( dbfreader.hasNextRecord()) {
				Map<String,String> map=new HashMap<String,String>();
				String aobj[] = dbfreader.nextRecordString();
				for (int b = 0; b < dbfreader.getFieldCount(); b++) {
					map.put(field[b], aobj[b].trim());
				}
				lm.add(map);
			}
		} catch (DBFException e) {
			e.printStackTrace();
		}
		return lm;
	}

	public static List<Stock> getStockInfo(List<Stock> stocks) {
		String filename=PropertyManager.getProperty("StockInfoFile");
		List<Map<String, String>> dbf = dbfToMapList(filename);

		for (Stock stock : stocks) {
			for (Map<String, String> map : dbf) {
				if (stock.getCode().equals(map.get("GPDM"))) {
					StockInfo info=stock.getStockinfo();
					info.setUpdateDate(map.get("GXRQ"));
					String zgb = map.get("ZGB");
					info.setTotals(Double.parseDouble(zgb)/ 10000.0);
					zgb = map.get("JLY");
					info.setNetProfit(Double.parseDouble(zgb)/100000.0);
					zgb = map.get("ZYSY");
					info.setRevenue(Double.parseDouble(zgb)/ 100000.0);
					break;
				}
			}
		}
		return stocks;
	}
	
	public static void main(String[] args) {
		List<Stock> stocks=getStockInfo(stockListFromFile());
		System.out.println(stocks.size());
		for (Stock stock:stocks){
			stock.loadMarketDataFromDiaryFile();
			System.out.println(stock.getCode()+"\t"+stock.getId()+"\t"+stock.getName()
					+"\t"+stock.getStockinfo().getUpdateDate()+"\t"+stock.getStockinfo().getNetProfit()
					+"\t"+stock.getStockinfo().getTotals()+"\t"+stock.getStockinfo().getMarketDay());
			stock.loadCaptialChangeData();
			List<CapitalChange> lcc=stock.getCapChanges();
			for (CapitalChange cc:lcc){
				System.out.println(DateTool.dateToString(cc.getDate(), "yyyy-MM-dd")+"\t"+cc.getTotal());
			}
			stock.loadEarningData(stock.getCapChanges());
			List<Earnings> les=stock.getEarnings();
			for (Earnings es:les){
				System.out.println(DateTool.dateToString(es.getDate(), "yyyy-MM-dd")+"\t"+es.getEps());
			}
			break;
		}

	}

}
